using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using STD.Shared.Infrastructure.Database;
using STD.Shared.Infrastructure.Caching;
using STD.Shared.Infrastructure.Messaging;

namespace STD.Shared.Common.Extensions;

/// <summary>
/// 服务集合扩展方法
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 添加共享服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddSharedServices(this IServiceCollection services, IConfiguration configuration)
    {
        // 添加数据库提供者
        services.AddDatabaseProvider(configuration);
        
        // 添加缓存服务
        services.AddCacheService(configuration);
        
        // 添加消息总线
        services.AddMessageBus(configuration);
        
        return services;
    }
    
    /// <summary>
    /// 添加数据库提供者
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    private static void AddDatabaseProvider(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<IDatabaseProviderFactory, DatabaseProviderFactory>();
        services.AddScoped<IDatabaseProvider>(provider =>
        {
            var factory = provider.GetRequiredService<IDatabaseProviderFactory>();
            var dbType = configuration.GetValue<string>("Database:Type") ?? "PostgreSQL";
            return factory.CreateProvider(dbType);
        });
    }
    
    /// <summary>
    /// 添加缓存服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    private static void AddCacheService(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<ICacheService, RedisCacheService>();
    }
    
    /// <summary>
    /// 添加消息总线
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    private static void AddMessageBus(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<IMessageBus, RabbitMQMessageBus>();
    }
} 